import 'package:flutter/material.dart';
import 'package:zpub_plugin/zpub_plugin.dart';
import 'package:zpub_bas/zpub_bas.dart';
import 'package:zpub_att/zpub_att.dart';
import 'package:zpub_dbmanager/zpub_dbmanager.dart';
import 'package:zpub_dbmanager/com/zerogis/zpubDbManager/bean/Plugin.dart';
import 'package:zpub_query/com/zerogis/zpubquery/plugin/QueryListPlugin.dart';
import 'package:zpub_svr/com/zerogis/zpubsvr/constant/HttpParamKeyValue.dart';

// INSERT INTO plugin(sys, cata, name, titlee, titlec, closeable, uitype, runn, dir, classurl, icon, service, initpara, height, width, modal, autorun, autoobj, prereq, container, button, align) VALUES('21', 'common', 'QueryPlugin', '综合查询', '综合查询', 1, 4, 1, 'package:mmdx/com/zerogis/mmdx/scene', 'QueryPlugin', '', '', '', 0, 0, 0, 0, NULL, NULL, NULL, NULL, 0);
/*
 * 综合查询主页 <br/>
 * 需要传入的键：<br/>
 * 传入的值类型： <br/>
 * 传入的值含义：<br/>
 * 是否必传 ：
 */
class QueryPlugin extends PluginStatefulBase
{
  QueryPlugin({Key key, plugin}) :super(key: key, plugin: plugin);

  State<StatefulWidget> createState()
  {
    return new QueryPluginState();
  }

  static String toStrings()
  {
    return "QueryPlugin";
  }
}

/*
 * 页面功能 <br/>
 */
class QueryPluginState extends PluginBaseState<QueryPlugin>
{
  /*
   * 属性主类型,属性子类型
   */
  int mMajor, mMinor;

  void initState()
  {
    super.initState();
  }

  Widget build(BuildContext context)
  {
    Widget widget = buildBody(
        context, SingleChildScrollView(child: Column(
      children: <Widget>[
        DropdownMenu(onChanged: (layer)
        {
          refreshAttWidget(layer);
        },),

        Card(child: Padding(padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10), child: Column(
            crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
          Chip(label: Text('条件', style: BasTextStyleRes.text_color_text1_larger_fontw900,),
            avatar: Image.asset('assets/images/ic_attributeitem.png'),
            labelPadding: EdgeInsets.only(left: 3), backgroundColor: Colors.white,),

          SysWidgetCreator.createCommonDevider(),
          createAttIsMCardEditWidget(),
        ]))),

        Align(child: IconButton(iconSize: 50, icon: Image.asset('assets/images/btn_location.png',), onPressed: ()
        {
          doClickQuery();
        }), alignment: Alignment.centerRight,)

      ],
    ),)
    );
    return widget;
  }

  void initData()
  {
    super.initData();
    LayerManager layerManager = LayerManager.getInstance();
    dynamic layer = layerManager.queryFirstChildLayer();
    mMajor = layer[DBFldConstant.FLD_MAJOR];
    mMinor = layer[DBFldConstant.FLD_MINOR];
  }

  Widget createAttIsMCardEditWidget()
  {
    return AttIsMCardEditWidget(
        mMajor, mMinor, plugin: new Plugin(), attState: 0, key: key_btn_border);
  }

  /*
   * 刷新属性组件
   */
  void refreshAttWidget(layer)
  {
    // 设置主子类型
    mMajor = layer[DBFldConstant.FLD_MAJOR];
    mMinor = layer[DBFldConstant.FLD_MINOR];

    // 刷新属性组件
    if (key_btn_border.currentState is AttIsMCardEditWidgetState)
    {
      AttIsMCardEditWidgetState state = key_btn_border.currentState;
      state.setState(()
      {
        state.refresh({DBFldConstant.FLD_MAJOR: mMajor, DBFldConstant.FLD_MINOR: mMinor});
      });
    }
  }


  /*
   * 点击查询
   */
  void doClickQuery()
  {
    AttIsMCardEditWidgetState state = key_btn_border.currentState;
    Map<String, dynamic> result = state.queryAttKeyExp();

    Map<String, dynamic> param = {
      DBFldConstant.FLD_MAJOR: mMajor,
      DBFldConstant.FLD_MINOR: mMinor,
      HttpParamKeyValue.PARAM_KEY_EXP: CxTextUtil.isEmpty(result[HttpParamKeyValue.PARAM_KEY_EXP])
          ? 'id>?'
          : result[HttpParamKeyValue.PARAM_KEY_EXP],
      HttpParamKeyValue.PARAM_KEY_TYPES: CxTextUtil.isEmpty(result[HttpParamKeyValue.PARAM_KEY_TYPES])
          ? 'i'
          : result[HttpParamKeyValue.PARAM_KEY_TYPES],
      HttpParamKeyValue.PARAM_KEY_VALS: CxTextUtil.isEmpty(result[HttpParamKeyValue.PARAM_KEY_VALS])
          ? '0'
          : result[HttpParamKeyValue.PARAM_KEY_VALS]
    };

//    Map<String, dynamic> param = {
//      DBFldConstant.FLD_MAJOR: mMajor,
//      DBFldConstant.FLD_MINOR: mMinor,
//      HttpParamKeyValue.PARAM_KEY_EXP: 'code LIKE ?',
//      HttpParamKeyValue.PARAM_KEY_TYPES: 's',
//      HttpParamKeyValue.PARAM_KEY_VALS: '%1%'
//    };
    PluginsFactory.getInstance().get(QueryListPlugin.toStrings()).runPlugin(this, initPara: param);
  }
}

/*
 * 类描述：综合查询顶部下拉菜单
 * 优化，如果DropdownMenu增多建议将下拉菜单和下拉单默认选择的值用集合装起来，参考原生写listview技巧
 *
 * 作者：郑朝军 on 2019/6/6
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2019/6/6
 * 修改备注：
 */
class DropdownMenu extends StatefulWidget
{
  /*
   * Menu数据回调方法
   */
  ValueChanged<dynamic> onChanged;

  DropdownMenu({this.onChanged, Key key}) :super(key: key);

  State<StatefulWidget> createState()
  {
    return new DropdownMenuState();
  }
}

class DropdownMenuState extends State<DropdownMenu>
{
  /*
   * 下拉菜单值
   */
  List<DropdownMenuItem> mDropdownMenuList = new List(),
      mDropdownMenuListSecond = new List();

  /*
   * 下拉菜单默认选择的值
   */
  dynamic mDropdownSelectMenuItem, mDropdownSelectMenuItemSecond;

  /*
   * 下拉菜单默认选择的值
   */
  LayerManagerConstant mLayerManager;

  void initState()
  {
    super.initState();
    initDropdownMenuList();
  }

  @override
  Widget build(BuildContext context)
  {
    return Card(child: Padding(padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
        Chip(label: Text('大类', style: BasTextStyleRes.text_color_text1_larger_fontw900,),
          avatar: Image.asset('assets/images/ic_majorclasses.png'),
          labelPadding: EdgeInsets.only(left: 3), backgroundColor: Colors.white,),
        Container(child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 5), child: createDropdownButton(),),
            decoration: BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill, image: AssetImage('assets/images/att_value_bg_clickable.png')),)),
        Chip(
          label: Text('子类', style: BasTextStyleRes.text_color_text1_larger_fontw900),
          avatar: Image.asset('assets/images/ic_classifications.png'),
          labelPadding: EdgeInsets.only(left: 3),
          backgroundColor: Colors.white,),
        Container(child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 5), child: createDropdownButton2(),),
            decoration: BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill, image: AssetImage('assets/images/att_value_bg_clickable.png')),)),
      ],),),);
  }

  /*
   * 初始化下拉菜单集合
   */
  void initDropdownMenuList()
  {
    mLayerManager = LayerManager.getInstance();
    // 取第一个dropdown数据
    List result = mLayerManager.queryChild('glid', 0);
    mDropdownSelectMenuItem = result.first;
    result.forEach((layer)
    {
      mDropdownMenuList.add(
          DropdownMenuItem(child: Text(layer['namec']), value: layer));
    });

    // 取第二个dropdown数据
    resetDropdownMenuSecond(mDropdownSelectMenuItem);
  }

  /*
   * 重置第二个DropdownMenu数据
   */
  void resetDropdownMenuSecond(layer)
  {
    mDropdownMenuListSecond.clear();
    List result = mLayerManager.queryChild('glid', layer['layer']);
    result.forEach((item)
    {
      mDropdownMenuListSecond.add(
          DropdownMenuItem(child: Text(item['namec']), value: item));
    });
    mDropdownSelectMenuItemSecond = result.first;

    // 修改子类菜单回调结果
    if (widget.onChanged != null)
    {
      widget.onChanged(mDropdownSelectMenuItemSecond);
    }
  }

  /*
   * 创建公有下拉菜单
   */
  Widget createDropdownButton()
  {
    return DropdownButtonHideUnderline(
      child: DropdownButton(
        isExpanded: true,
        value: mDropdownSelectMenuItem,
        items: mDropdownMenuList,
        onChanged: (layer)
        {
          setState(()
          {
            mDropdownSelectMenuItem = layer;

            // 设置第二个
            resetDropdownMenuSecond(layer);
          });
        },
      ),
    );
  }

  /*
   * 创建公有下拉菜单
   */
  Widget createDropdownButton2()
  {
    return DropdownButtonHideUnderline(child: DropdownButton(
      isExpanded: true,
      value: mDropdownSelectMenuItemSecond,
      items: mDropdownMenuListSecond,
      onChanged: (layer)
      {
        setState(()
        {
          mDropdownSelectMenuItemSecond = layer;

          // 修改子类菜单回调结果
          if (widget.onChanged != null)
          {
            widget.onChanged(mDropdownSelectMenuItemSecond);
          }
        });
      },
    ),);
  }
}


/*
 * 类描述：**模块提供的Service其他模块调用本模块对外提供的相关方法
 * 作者：郑朝军 on 2019/6/6
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2019/6/6
 * 修改备注：
 */
class QueryPluginService extends InterfaceBaseImpl
{
  @override
  Future<T> runPlugin<T extends Object>(State<StatefulWidget> state,
      {dynamic initPara})
  {
    return StateManager.getInstance().startWidegtState(new QueryPlugin(), state);
  }

  @override
  Widget runWidget({dynamic initPara})
  {
    return new QueryPlugin();
  }
}
